//
// Created by Tian on 25-5-2.
//

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "esp_log.h"

#include "lvgl.h"
#include "lv_port_disp.h"
#include "ui.h"

#include "lcd.h"
#include "lcd_init.h"
#include "lcd_def.h"
#include "lcd_function.h"


#define TAG __FILE__

static SemaphoreHandle_t lvgl_mutex = NULL;  // 全局 LVGL 互斥锁


void lvgl_thread_lock(void)
{
    if(lvgl_mutex)
        xSemaphoreTake(lvgl_mutex, portMAX_DELAY);
}

void lvgl_thread_unlock(void)
{
    if(lvgl_mutex)
        xSemaphoreGive(lvgl_mutex);
}


void lcd_refresh_task(void* arg)
{
    if(lcd_init(LCD_W, LCD_H) != 0)
    {
        ESP_LOGE(TAG, "lcd_init_err!");
        vTaskDelete(NULL);
        return;
    }
    lvgl_mutex = xSemaphoreCreateMutex();
    assert((lvgl_mutex != NULL));

    lcd_frame_buff_init(LCD_W, LCD_H);
    lv_init();
    lv_port_disp_init();
    ui_init();

    while (1)
    {
        if (xSemaphoreTake(lvgl_mutex, portMAX_DELAY) == pdTRUE) {
            lv_task_handler();  // 执行 LVGL 主循环
            lcd_frame_refresh();
            xSemaphoreGive(lvgl_mutex);  // 释放锁
        }
        vTaskDelay(pdMS_TO_TICKS(10));
    }
}

void lcd_task_init(void)
{
    xTaskCreate(lcd_refresh_task, "lcd_refresh_task", 4096, NULL, 10, NULL);
}
